﻿using System.Collections;
using System.Windows.Forms;

namespace PlaylistEditorForCentrafuse.GUI
{
    class ListViewColumnSorter : IComparer
    {
        public int SortColumn { get; set; }
        public SortOrder SortOrder { get; set; }
        
        private CaseInsensitiveComparer _objectComparer = new CaseInsensitiveComparer();
        private int[] _numericColumns;

        public ListViewColumnSorter(int[] i_numericColumns)
        {
            _numericColumns = i_numericColumns;

            SortColumn = 0;
            SortOrder = SortOrder.None;
        }

        public int Compare(object x, object y)
        {
            ListViewItem listItemX = x as ListViewItem;
            ListViewItem listItemY = y as ListViewItem;

            // Numerisch ?
            bool numeric = false;
            foreach (int i in _numericColumns)
            {
                if (i == SortColumn)
                {
                    numeric = true;
                    break;
                }
            }

            // Spalteneinträge vergleichen
            int compareResult;
            if (numeric)
            {
                // Numerisch vergleichen
                compareResult = CompareNumeric(listItemX.SubItems[SortColumn].Text,
                                               listItemY.SubItems[SortColumn].Text);
            }
            else
            {
                // Zeichenfolge vergleichen
                compareResult = _objectComparer.Compare(listItemX.SubItems[SortColumn].Text, 
                                                        listItemY.SubItems[SortColumn].Text);
            }

            // Sortierreihenfolge
            if (SortOrder == SortOrder.Ascending)
            {
                return compareResult;
            }
            else if (SortOrder == SortOrder.Descending)
            {
                return -compareResult;
            }
            else
            {
                return 0;
            }
        }

        private int CompareNumeric(string i_x, string i_y)
        { 
            int x = int.Parse(i_x);
            int y = int.Parse(i_y);

            if (x < y)
            {
                return -1;
            }
            else if (x > y)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }
}
